#include "farmdiarywindow.h"
#include <QDebug>

FarmDiaryWindow::FarmDiaryWindow(QWidget *parent)
    : QMainWindow(parent)
{
    // 窗口设置
    setWindowTitle("农场日记 - 种植分享社区");
    setMinimumSize(1000, 700);

    // 先创建主部件再应用样式
    createMainWidget();
    createActions();
    createToolBar();
    createStatusBar();

    applyStyle();

    toolbarNickname->setText("农场主");
}

QScrollArea* FarmDiaryWindow::getImageScrollArea()
{
    // 直接在detailWidget中找到QScrollArea对象
    return detailWidget->findChild<QScrollArea*>("imageScrollArea");
}

void FarmDiaryWindow::showPostList()
{
    stackedWidget->setCurrentIndex(0);
    buyButton->hide(); // 隐藏购买按钮
}

void FarmDiaryWindow::showCreatePost()
{
    stackedWidget->setCurrentIndex(1);
}

void FarmDiaryWindow::updateProfileData()
{
    accountEdit->setText(oa_username);
    passwordEdit->setText(oa_password);
}

void FarmDiaryWindow::showPostDetail()
{
    // 获取当前选中的帖子项
    QListWidgetItem *item = postList->currentItem();
    if (!item) return;

    // 获取关联的PostItemWidget
    PostItemWidget *widget = qobject_cast<PostItemWidget*>(postList->itemWidget(item));
    if (!widget) return;

    // 设置详情视图数据
    detailTitleLabel->setText(widget->getTitle());
    detailAuthorLabel->setText("发布者: " + widget->getAuthor());
    detailTimeLabel->setText("发布于: " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm"));
    detailContentLabel->setText(widget->getContent());
    detailPlantLabel->setText("作物: " + widget->getPlantType());
    detailPriceLabel->setText("出价: ¥" + QString::number(widget->getPrice(), 'f', 2));

    // 启用购买按钮
    buyButton->setEnabled(true);
    buyButton->show();

    // 重置图片标签
    detailImageLabel->setPixmap(QPixmap());
    detailImageLabel->clear();
    detailImageLabel->setAlignment(Qt::AlignCenter);
    detailImageLabel->setScaledContents(false);
    detailImageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    detailImageLabel->setMinimumSize(200, 150);

    // 加载图片
    if (!widget->getImagePath().isEmpty()) {
        QPixmap pixmap(widget->getImagePath());
        if (!pixmap.isNull()) {
            // 获取滚动区域
            QScrollArea* scrollArea = getImageScrollArea();
            if (!scrollArea) {
                qWarning() << "滚动区域未找到!";
                return;
            }

            // 获取实际可用空间（减去内边距）
            int maxWidth = scrollArea->viewport()->width() - 10; // 减去内边距
            int maxHeight = scrollArea->viewport()->height() - 10; // 减去内边距

            // 计算保持宽高比的最佳尺寸
            double aspectRatio = static_cast<double>(pixmap.width()) / pixmap.height();
            int scaledWidth, scaledHeight;

            if (maxWidth / aspectRatio <= maxHeight) {
                scaledWidth = maxWidth;
                scaledHeight = static_cast<int>(maxWidth / aspectRatio);
            } else {
                scaledHeight = maxHeight;
                scaledWidth = static_cast<int>(maxHeight * aspectRatio);
            }

            // 应用缩放
            QPixmap scaled = pixmap.scaled(
                scaledWidth,
                scaledHeight,
                Qt::KeepAspectRatio,
                Qt::SmoothTransformation
            );

            // 更新图片
            detailImageLabel->setScaledContents(true); // 启用缩放内容
            detailImageLabel->setPixmap(scaled);
            detailImageLabel->setFixedSize(scaled.size()); // 设置固定尺寸匹配缩放后大小

            // 重置滚动位置
            scrollArea->verticalScrollBar()->setValue(0);
            scrollArea->horizontalScrollBar()->setValue(0);
        }
    } else {
        detailImageLabel->setText("(无图片)");
    }

    stackedWidget->setCurrentIndex(2);
}

void FarmDiaryWindow::submitPost()
{
    QString title = titleEdit->text();
    QString content = contentEdit->toPlainText();
    QString plantType = plantCombo->currentText();
    float price = priceSpin->value();

    if(title.isEmpty() || content.isEmpty()) {
        QMessageBox::warning(this, "提交失败", "请填写标题和内容");
        return;
    }

    // 添加到帖子列表
    QListWidgetItem *item = new QListWidgetItem;
    item->setSizeHint(QSize(0, 240));

    PostItemWidget *widget = new PostItemWidget;
    widget->setPostData("当前用户", title + "\n" + content,
                      plantType, price, imagePath); // 传递图片路径

    postList->addItem(item);
    postList->setItemWidget(item, widget);

    // 清空表单
    titleEdit->clear();
    contentEdit->clear();
    priceSpin->setValue(0);

    // 返回列表视图
    showPostList();
    statusBar()->showMessage("卖单发布成功！", 3000);

    // 重置图片状态
    imagePath = ""; // 清空路径
    imageLabel->setText("未选择图片"); // 更新UI提示
}

void FarmDiaryWindow::selectImage()
{
    QString filePath = QFileDialog::getOpenFileName(
        this, "选择植物图片", "", "图片文件 (*.png *.jpg *.jpeg)");

    if(!filePath.isEmpty()) {
        // 实际应用中应处理图片上传/压缩
        imagePath = filePath;
        imageLabel->setText("已选择图片: " + QFileInfo(filePath).fileName());
    }
}

void FarmDiaryWindow::applyStyle()
{
        // 设置全局样式
        qApp->setStyle(QStyleFactory::create("Fusion"));

        // 自定义配色方案
        QString style = R"(
            QMainWindow {
                background-color: #f5f7fa;
            }
            QToolBar {
                background-color: #3498db;
                border: none;
                padding: 4px;
            }
            QToolButton {
                color: white;
                padding: 6px 12px;
                border-radius: 4px;
            }
            QToolButton:hover {
                background-color: #2980b9;
            }
            QListWidget {
                background-color: white;
                border: none;
                border-radius: 8px;
            }
            QTextEdit, QLineEdit, QComboBox, QSpinBox {
                border: 1px solid #ddd;
                border-radius: 4px;
                padding: 8px;
                font-size: 14px;
            }
            QPushButton {
                background-color: #27ae60;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #219653;
            }
                        QTabWidget::pane {
                            border: 1px solid #ddd;
                            border-radius: 8px;
                        }
                        QTabBar::tab {
                            background: #f8f9fa;
                            padding: 8px 16px;
                            border-top-left-radius: 4px;
                            border-top-right-radius: 4px;
                        }
                        QTabBar::tab:selected {
                            background: #27ae60;
                            color: white;
                        }

                        QLineEdit, QComboBox {
                            min-height: 30px;
                            padding: 6px;
                        }
            QGroupBox {
                border: 1px solid #ddd;
                border-radius: 8px;
                margin-top: 16px;
                font-weight: bold;
            }
                        PostItemWidget {
                            padding: 15px;
                            border-bottom: 1px solid #eee;  // 项间分隔线
                        }
                        QLabel#contentLabel {
                            margin-top: 8px;  // 文字与图片间距
                            max-width: 300px;  // 限制文字宽度防溢出
                        }
        )";

        style += R"(
            /* 图片区域容器样式 */
            QScrollArea#imageScrollArea {
                background: #f8f9fa;
                border: 1px solid #e0e0e0;
                border-radius: 8px;
                margin-bottom: 15px;
                min-height: 200px; /* 确保最小高度 */
            }

            /* 图片标签样式 */
            QLabel#detailImageLabel {
                background: transparent;
            }
        )";

        qApp->setStyleSheet(style);
    }

    void FarmDiaryWindow::createMainWidget()
    {
        QWidget *centralWidget = new QWidget;
        setCentralWidget(centralWidget);

        QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
        mainLayout->setSpacing(16);
        mainLayout->setContentsMargins(16, 16, 16, 16);

        // 创建堆栈窗口管理不同视图
        stackedWidget = new QStackedWidget;

        // 1. 商品列表视图
        postList = new QListWidget;
        postList->setSelectionMode(QAbstractItemView::SingleSelection);
        connect(postList, &QListWidget::itemDoubleClicked, this, &FarmDiaryWindow::showPostDetail);

        // 添加示例帖子
        for(int i = 0; i < 5; ++i) {
            QListWidgetItem *item = new QListWidgetItem;
            item->setSizeHint(QSize(0, 240));

            PostItemWidget *widget = new PostItemWidget;
            widget->setPostData(
                QString("农场主%1").arg(i+1),
                QString("这是我种植的第%1批番茄，使用有机肥料，生长情况良好...").arg(i+1),
                "番茄",
                98.0 + i*20
            );

            postList->addItem(item);
            postList->setItemWidget(item, widget);

        }

        // 2. 发布商品视图
        QWidget *createWidget = new QWidget;
        QVBoxLayout *createLayout = new QVBoxLayout(createWidget);

        // 表单区域
        QGroupBox *formGroup = new QGroupBox("发布新商品");
        QFormLayout *formLayout = new QFormLayout(formGroup);

        titleEdit = new QLineEdit;
        titleEdit->setPlaceholderText("输入商品标题");

        contentEdit = new QTextEdit;
        contentEdit->setPlaceholderText("详细描述您的种植经验...");
        contentEdit->setMinimumHeight(150);

        plantCombo = new QComboBox;
        plantCombo->addItems({"番茄", "黄瓜", "草莓", "生菜", "胡萝卜", "蓝莓","自定义"});

        priceSpin = new QDoubleSpinBox;
        priceSpin->setRange(0, 10000);
        priceSpin->setPrefix("¥ ");
        priceSpin->setValue(98);

        // 图片选择
        QWidget *imageWidget = new QWidget;
        QHBoxLayout *imageLayout = new QHBoxLayout(imageWidget);
        imageLayout->setContentsMargins(0, 0, 0, 0);

        QPushButton *selectImageBtn = new QPushButton("选择图片");
        connect(selectImageBtn, &QPushButton::clicked, this, &FarmDiaryWindow::selectImage);

        imageLabel = new QLabel("未选择图片");
        imageLabel->setStyleSheet("color: #7f8c8d;");

        imageLayout->addWidget(selectImageBtn);
        imageLayout->addWidget(imageLabel, 1);

        // 添加到表单
        formLayout->addRow("标题:", titleEdit);
        formLayout->addRow("内容:", contentEdit);
        formLayout->addRow("作物类型:", plantCombo);
        formLayout->addRow("出价:", priceSpin);
        formLayout->addRow("图片:", imageWidget);

        // 提交按钮
        QPushButton *submitBtn = new QPushButton("发布商品");
        submitBtn->setFixedHeight(40);
        connect(submitBtn, &QPushButton::clicked, this, &FarmDiaryWindow::submitPost);

        createLayout->addWidget(formGroup);
        createLayout->addWidget(submitBtn);
        createLayout->addStretch();

        // 帖子详情视图（重要修改部分）：
        detailWidget = new QWidget;
        QVBoxLayout *detailLayout = new QVBoxLayout(detailWidget);
        detailLayout->setSpacing(15);
        detailLayout->setContentsMargins(25, 25, 25, 25);

        // 返回按钮
        QPushButton *backBtn = new QPushButton("返回列表");
        backBtn->setFixedSize(100, 35);
        connect(backBtn, &QPushButton::clicked, this, &FarmDiaryWindow::showPostList);

        // 创建详情显示控件
        detailTitleLabel = new QLabel;
        detailTitleLabel->setStyleSheet("font-size: 20px; font-weight: bold;");

        QWidget *metaWidget = new QWidget;
        QHBoxLayout *metaLayout = new QHBoxLayout(metaWidget);
        metaLayout->setContentsMargins(0, 0, 0, 0);

        detailAuthorLabel = new QLabel;
        detailAuthorLabel->setStyleSheet("color: #3498db;");

        detailTimeLabel = new QLabel;
        detailTimeLabel->setStyleSheet("color: #95a5a6; font-size: 13px;");

        metaLayout->addWidget(detailAuthorLabel);
        metaLayout->addSpacing(15);
        metaLayout->addWidget(detailTimeLabel);
        metaLayout->addStretch();

        // === 图片区域 ===
        QScrollArea *imageScrollArea = new QScrollArea;
        imageScrollArea->setObjectName("imageScrollArea"); // 设置唯一对象名
        imageScrollArea->setWidgetResizable(true);
        imageScrollArea->setFrameShape(QFrame::NoFrame);
        imageScrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        imageScrollArea->setMinimumHeight(200); // 设置最小高度

        // 图片容器
        QWidget *imageContainer = new QWidget;
        QVBoxLayout *imageContainerLayout = new QVBoxLayout(imageContainer);
        imageContainerLayout->setContentsMargins(0, 0, 0, 0);
        imageContainerLayout->setAlignment(Qt::AlignCenter); // 添加居中布局

        detailImageLabel = new QLabel;
        detailImageLabel->setObjectName("detailImageLabel");
        detailImageLabel->setAlignment(Qt::AlignCenter);
        detailImageLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

        // 添加边距和设置缩放属性
        detailImageLabel->setStyleSheet("padding: 5px;");
        detailImageLabel->setScaledContents(true);

        imageContainerLayout->addWidget(detailImageLabel);
        imageContainer->setLayout(imageContainerLayout);
        imageScrollArea->setWidget(imageContainer);
        // === 文本区域修改：添加滚动区域 ===
        QScrollArea *contentScroll = new QScrollArea;
        contentScroll->setWidgetResizable(true);
        contentScroll->setFrameShape(QFrame::NoFrame); // 无边框

        QWidget *contentWidget = new QWidget;
        QVBoxLayout *contentLayout = new QVBoxLayout(contentWidget);
        contentLayout->setContentsMargins(0, 0, 0, 0);

        detailContentLabel = new QTextEdit;
        detailContentLabel->setObjectName("detailContentLabel"); // 设置对象名用于样式表
        detailContentLabel->setReadOnly(true);
        detailContentLabel->setStyleSheet(
            "border: 1px solid #e0e0e0;"
            "border-radius: 8px;"
            "padding: 15px;"
            "background: white;"
            "margin-top: 10px;" // 关键：添加上边距防止重叠
        );

        contentLayout->addWidget(detailContentLabel);
        contentWidget->setLayout(contentLayout);
        contentScroll->setWidget(contentWidget);

        // === 信息区域 ===
        QWidget *infoWidget = new QWidget;
        QHBoxLayout *infoLayout = new QHBoxLayout(infoWidget);
        infoLayout->setContentsMargins(0, 0, 0, 0);

        detailPlantLabel = new QLabel;
        detailPlantLabel->setStyleSheet(
            "background: #27ae60;"
            "color: white;"
            "padding: 5px 15px;"
            "border-radius: 15px;"
        );

        detailPriceLabel = new QLabel;
        detailPriceLabel->setStyleSheet(
            "font-weight: bold;"
            "font-size: 16px;"
            "color: #e74c3c;"
        );

        infoLayout->addWidget(detailPlantLabel);
        infoLayout->addStretch();
        infoLayout->addWidget(detailPriceLabel);

        // === 组装布局 ===
        detailLayout->addWidget(backBtn, 0, Qt::AlignLeft);
        detailLayout->addSpacing(20);
        detailLayout->addWidget(detailTitleLabel);
        detailLayout->addWidget(metaWidget);
        detailLayout->addSpacing(15);
        detailLayout->addWidget(imageScrollArea, 1);
        detailLayout->addSpacing(15);
        detailLayout->addWidget(contentScroll, 1);

        // 购买按钮
        buyButton = new QPushButton("立即购买");
        buyButton->setFixedSize(120, 40);
        buyButton->setStyleSheet(
            "background-color: #e74c3c;"
            "color: white;"
            "font-weight: bold;"
            "font-size: 16px;"
            "border-radius: 6px;"
            "margin-top: 10px;" // 添加上边距
        );

        detailLayout->addSpacing(15);
        detailLayout->addWidget(buyButton, 0, Qt::AlignRight);
        connect(buyButton, &QPushButton::clicked, this, &FarmDiaryWindow::handlePurchase);

        // ================= 4. 社区论坛页面 =================
        QWidget *forumWidget = new QWidget;
        QVBoxLayout *forumLayout = new QVBoxLayout(forumWidget);

        // 创建选项卡
        forumTabs = new QTabWidget(forumWidget);
        qnaList = new QListWidget;      // 问答区
        expList = new QListWidget;       // 经验分享区
        tradeList = new QListWidget;    // 交易互助区

        // 添加示例内容
        qnaList->addItem("Q: 番茄叶面发黄怎么办？");
        expList->addItem("经验：有机草莓种植的5个关键技巧");
        tradeList->addItem("求购：有机肥料200公斤");

        forumTabs->addTab(qnaList, "问答区");
        forumTabs->addTab(expList, "经验分享");
        forumTabs->addTab(tradeList, "交易互助");

        forumLayout->addWidget(forumTabs);

        // ================= 5. 个人中心页面 =================
        profileWidget = new QWidget;
        QFormLayout *profileLayout = new QFormLayout(profileWidget);

        // 个人信息设置
        avatarBtn = new QPushButton("选择头像");
        nicknameEdit = new QLineEdit("农场主");
        QPushButton *saveBtn = new QPushButton("保存设置");

        // 隐私设置
        privacyCombo = new QComboBox;
        privacyCombo->addItems({"公开资料", "仅粉丝可见", "完全私密"});

        // 添加账号安全分组框
        QGroupBox *securityGroup = new QGroupBox("账号安全");
        QFormLayout *securityLayout = new QFormLayout(securityGroup);

        QLabel *accountLabel = new QLabel("账号:");
        accountEdit = new QLineEdit();
        accountEdit->setText(oa_username);
        accountEdit->setReadOnly(true);  // 账号不可编辑

        // 密码显示控件（带显示/隐藏按钮）
        passwordEdit = new QLineEdit();
        passwordEdit->setEchoMode(QLineEdit::Password);
        passwordEdit->setText(oa_password);
        QPushButton *showPwdBtn = new QPushButton("显示");
        connect(showPwdBtn, &QPushButton::pressed, [=](){
            passwordEdit->setEchoMode(QLineEdit::Normal);
        });
        connect(showPwdBtn, &QPushButton::released, [=](){
            passwordEdit->setEchoMode(QLineEdit::Password);
        });

        // 修改密码按钮
        QPushButton *changePwdBtn = new QPushButton("修改密码");
        //connect(changePwdBtn, &QPushButton::clicked, this, &FarmDiaryWindow::showChangePasswordDialog);

        securityLayout->addRow(accountLabel, accountEdit);
        securityLayout->addRow(new QLabel("密码:"), passwordEdit);
        securityLayout->addRow(showPwdBtn, changePwdBtn);
        profileLayout->addWidget(securityGroup);

        // 布局
        profileLayout->addRow("头像:", avatarBtn);
        profileLayout->addRow("昵称:", nicknameEdit);
        profileLayout->addRow("隐私设置:", privacyCombo);
        profileLayout->addRow(saveBtn);

        stackedWidget->addWidget(postList);
        stackedWidget->addWidget(createWidget);
        stackedWidget->addWidget(detailWidget);
        stackedWidget->addWidget(forumWidget);
        stackedWidget->addWidget(profileWidget);

        mainLayout->addWidget(stackedWidget);

        QStringList qnaItems = {"Q: 番茄叶面发黄怎么办？", "Q: 有机肥料如何自制？"};
        QStringList expItems = {"经验：草莓越冬管理技巧", "分享：黄瓜病虫害防治方法"};
        QStringList tradeItems = {"求购：有机肥料200公斤", "出售：优质番茄种子"};

        qnaList->addItems(qnaItems);
        expList->addItems(expItems);
        tradeList->addItems(tradeItems);

        // 启用双击信号
        connect(qnaList, &QListWidget::itemDoubleClicked, this, &FarmDiaryWindow::showForumPostDetail);
        connect(expList, &QListWidget::itemDoubleClicked, this, &FarmDiaryWindow::showForumPostDetail);
        connect(tradeList, &QListWidget::itemDoubleClicked, this, &FarmDiaryWindow::showForumPostDetail);

        // ================= 添加个人中心头像/昵称更新逻辑 =================
        // 连接头像按钮信号
        connect(avatarBtn, &QPushButton::clicked, this, [=](){
            QString filePath = QFileDialog::getOpenFileName(
                this, "选择头像", "", "图片文件 (*.png *.jpg *.jpeg)");

            if(!filePath.isEmpty()) {
                // 更新右上角头像
                updateToolbarAvatar(filePath);
            }
        });

        // 连接保存按钮信号 - 使用上面已定义的saveBtn
        connect(saveBtn, &QPushButton::clicked, this, [=](){
            // 更新右上角昵称
            toolbarNickname->setText(nicknameEdit->text());
            statusBar()->showMessage("个人资料已更新", 2000);
        });

        // ======= 发帖界面 =======
        QWidget *forumPostWidget = new QWidget;
        QFormLayout *postLayout = new QFormLayout(forumPostWidget);

        // 成员变量声明（在FarmDiaryWindow.h中添加）
        forumTypeCombo = new QComboBox;      // 替换postTypeCombo
        forumTitleEdit = new QLineEdit;       // 替换postTitleEdit
        forumContentEdit = new QTextEdit;      // 替换postContentEdit
        forumPriceSpin = new QDoubleSpinBox;   // 替换priceSpin

        forumTypeCombo->addItems({"问答", "经验分享", "交易互助"});
        forumPriceSpin->setRange(0, 10000);   // 设置价格范围
        forumPriceSpin->setPrefix("¥ ");

        // 动态显示价格字段
        connect(forumTypeCombo,
                static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
                [=](int index) {
                    forumPriceSpin->setVisible(index == 2);
                });

        postLayout->addRow("类型:", forumTypeCombo);
        postLayout->addRow("标题:", forumTitleEdit);
        postLayout->addRow("内容:", forumContentEdit);
        //postLayout->addRow("价格:", forumPriceSpin);
        forumPriceSpin->setVisible(false); // 初始隐藏

        QPushButton *submitPostBtn = new QPushButton("发布");
        connect(submitPostBtn, &QPushButton::clicked, this, &FarmDiaryWindow::submitForumPost);
        postLayout->addRow(submitPostBtn);

        stackedWidget->addWidget(forumPostWidget); // 索引5
    }

    void FarmDiaryWindow::showForumPostDetail(QListWidgetItem *item)
    {
        // 获取当前选中的版块类型（问答/经验/交易）
        int tabIndex = forumTabs->currentIndex();
        QString tabName = forumTabs->tabText(tabIndex);

        // 设置详情页数据
        detailTitleLabel->setText(item->text());
        detailAuthorLabel->setText("发布者: 社区用户");
        detailContentLabel->setText("这里是帖子详细内容...");
        detailPlantLabel->setText("版块: " + tabName);

        // 隐藏价格标签
        detailPriceLabel->setVisible(tabIndex == 2); // 仅交易版显示价格
        buyButton->setVisible(false);

        detailImageLabel->setText("(社区贴子图片)");
        detailImageLabel->setStyleSheet("font-size: 16px; color: #95a5a6;");

        // === 添加社区特定图片逻辑 ===
        QString forumType = forumTabs->tabText(tabIndex).left(2); // 获取前2字符

        // 示例：根据论坛类型设置不同图片
        QPixmap forumPix;
        if(forumType == "问答") {
            forumPix = QPixmap(":/images/question.png"); // 问答图标
        }
        else if(forumType == "经验") {
            forumPix = QPixmap(":/images/experience.png"); // 经验图标
        }
        else if(forumType == "交易") {
            forumPix = QPixmap(":/images/trade.png"); // 交易图标
        }

        if(!forumPix.isNull()) {
            forumPix = forumPix.scaled(120, 120, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            detailImageLabel->setPixmap(forumPix);
            detailImageLabel->setStyleSheet(""); // 重置样式
        }


        stackedWidget->setCurrentIndex(2); // 跳转到详情页
    }

    void FarmDiaryWindow::handlePurchase()
    {
        // 获取当前显示的帖子
        QListWidgetItem *item = postList->currentItem();
        if (!item) return;

        PostItemWidget *widget = qobject_cast<PostItemWidget*>(postList->itemWidget(item));
        if (!widget) return;

        // 获取商品信息
        QString productName = widget->getTitle();
        QString author = widget->getAuthor();
        double price = widget->getPrice();

        // 创建购买确认对话框
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, "确认购买",
                                     QString("确定要购买【%1】的%2吗？\n价格: ¥%3")
                                     .arg(author)
                                     .arg(productName)
                                     .arg(price, 0, 'f', 2),
                                     QMessageBox::Yes | QMessageBox::No);

        if (reply == QMessageBox::Yes) {
            // 模拟购买处理
            QTimer::singleShot(1500, [=]() {
                // 显示购买成功消息
                statusBar()->showMessage(QString("成功购买%1的%2！").arg(author).arg(productName), 5000);

                // 显示订单信息
                QMessageBox::information(this, "购买成功",
                                         QString("订单详情：\n\n"
                                                 "商品：%1\n"
                                                 "卖家：%2\n"
                                                 "价格：¥%3\n\n"
                                                 "订单已生成，请等待卖家联系发货。")
                                         .arg(productName)
                                         .arg(author)
                                         .arg(price, 0, 'f', 2));
            });

            // 显示加载状态
            statusBar()->showMessage("正在处理购买请求...");
            buyButton->setEnabled(false);
            QApplication::setOverrideCursor(Qt::WaitCursor);
        }
    }

    void FarmDiaryWindow::submitForumPost() {
        QString type = forumTypeCombo->currentText();
        QString title = forumTitleEdit->text();
        QString content = forumContentEdit->toPlainText();
        double price = forumPriceSpin->value();

        // 验证输入
        if(title.isEmpty() || content.isEmpty()) {
            QMessageBox::warning(this, "提交失败", "标题和内容不能为空！");
            return;
        }

        // 根据类型添加到对应列表
        QListWidget *targetList = nullptr;
        if(type == "问答") targetList = qnaList;
        else if(type == "经验分享") targetList = expList;
        else if(type == "交易互助") targetList = tradeList;

        if(targetList) {
            targetList->addItem(title);
            // 实际应存储完整数据对象
            statusBar()->showMessage(type + "发布成功！", 3000);
        }

        stackedWidget->setCurrentIndex(3); // 返回论坛主页
    }

    void FarmDiaryWindow::createActions()
    {
        homeAction = new QAction("商品列表", this);
        connect(homeAction, &QAction::triggered, this, &FarmDiaryWindow::showPostList);

        createAction = new QAction("发布商品", this);
        connect(createAction, &QAction::triggered, this, &FarmDiaryWindow::showCreatePost);

        forumAction = new QAction("社区论坛", this);
        connect(forumAction, &QAction::triggered, [=](){
            stackedWidget->setCurrentIndex(3);
        });

        m_profileAction = new QAction("个人中心", this);
        connect(m_profileAction, &QAction::triggered, [=](){
            stackedWidget->setCurrentIndex(4);
        });

        newPostAction = new QAction("发帖", this);
        connect(newPostAction, &QAction::triggered, [=](){
            stackedWidget->setCurrentIndex(5); // 跳转发帖页
            // 重置表单
                forumTypeCombo->setCurrentIndex(0);
                forumTitleEdit->clear();
                forumContentEdit->clear();
                forumPriceSpin->setValue(0);
                forumPriceSpin->setVisible(false);

                stackedWidget->setCurrentIndex(5); // 跳转发帖页
        });
    }

    void FarmDiaryWindow::createToolBar()
    {
        QToolBar *toolbar = addToolBar("主菜单");
        toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
        toolbar->setMovable(false);

        toolbar->addAction(homeAction);
        toolbar->addAction(createAction);
        toolbar->addAction(forumAction);
        toolbar->addAction(m_profileAction);
        toolbar->addAction(newPostAction);
        toolbar->addSeparator();

        // ================= 添加右上角用户信息区域 =================
        QWidget *spacer = new QWidget();
        spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        toolbar->addWidget(spacer);

        // 用户信息容器
        userInfoWidget = new QWidget(toolbar);
        QHBoxLayout *userLayout = new QHBoxLayout(userInfoWidget);
        userLayout->setContentsMargins(0, 0, 15, 0);
        userLayout->setSpacing(10);

        // 头像显示（圆形）
        toolbarAvatar = new QLabel(userInfoWidget);
        toolbarAvatar->setFixedSize(36, 36);  // 固定大小
        toolbarAvatar->setAlignment(Qt::AlignCenter);
        toolbarAvatar->setStyleSheet(
            "background-color: #e0e0e0;"
            "border-radius: 18px;"  // 圆形效果
            "border: 1px solid rgba(255,255,255,0.3);"
        );
        toolbarAvatar->setText("头像");  // 默认文本

        // 昵称显示
        toolbarNickname = new QLabel("未登录", userInfoWidget);
        toolbarNickname->setStyleSheet(
            "color: white;"
            "font-size: 14px;"
            "font-weight: bold;"
        );

        // 添加到布局
        userLayout->addWidget(toolbarAvatar);
        userLayout->addWidget(toolbarNickname);
        userInfoWidget->setLayout(userLayout);

        // 添加到工具栏
        toolbar->addWidget(userInfoWidget);
    }

    void FarmDiaryWindow::createStatusBar()
    {
        statusBar()->showMessage("欢迎来到农场日记社区！");
    }

    // 更新工具栏头像的函数
    void FarmDiaryWindow::updateToolbarAvatar(const QString &path)
    {
        QPixmap pixmap(path);
        if (!pixmap.isNull()) {
            // 创建圆形头像
            QPixmap circle(36, 36);
            circle.fill(Qt::transparent);

            QPainter painter(&circle);
            painter.setRenderHint(QPainter::Antialiasing, true);
            painter.setBrush(QBrush(pixmap.scaled(36, 36, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)));
            painter.setPen(Qt::NoPen);
            painter.drawEllipse(0, 0, 36, 36);

            toolbarAvatar->setPixmap(circle);
        } else {
            toolbarAvatar->setText("头像");
            toolbarAvatar->setStyleSheet(
                "background-color: #e0e0e0;"
                "border-radius: 18px;"
                "color: #666;"
                "font-size: 12px;"
            );
        }
    }

    void FarmDiaryWindow::closeEvent(QCloseEvent *event)
    {
        emit exit();       // 在窗口关闭前发出信号
    }

FarmDiaryWindow::~FarmDiaryWindow()
{
}

